var layer = layui.layer //弹层
    , table = layui.table //表格
    , upload = layui.upload
    , userphotos = "",
    form = layui.form, $ = layui.jquery, id = getQueryVariable("id"),
    img_count = 0, file_count = 0, maincode = "", imgs = [], wjs = [];
let selectdata = [];


form.render();
//单位
let dw = getdictionary(3, 10);
//采购币种
let cgbz = getdictionary(5, 14);
//海关
let hs = getdictionary(3, 8);
let gys = getgys();
//附件规格型号
let fjCode = "";
let cataCodeName = JSON.parse(window.sessionStorage.getItem("cataCodeName"));
let cataCode = JSON.parse(window.sessionStorage.getItem("cataCode"));
let cataCodeMo = window.sessionStorage.getItem('cataCodeMo');
let code = "";
if (id != "") {
    code = JSON.parse(window.sessionStorage.getItem("code"));//产品编码
}

//客户等级
let hsselect = $("select[name='hgCode']");
hsselect.append(getoptionHs(hs));

form.on("select(hgCodeFilter)", function (data) {
    var hg = data.value;
    for (var i = 0; i < hs.length; i++) {
        if (hg == hs[i].code) {
            $("input[name='vatRate']")[0].value = hs[i].vatRate;
            $("input[name='taxRate']")[0].value = hs[i].taxRate;
            $("input[name='importTariff']")[0].value = hs[i].importTariff;
            break;
        } else {
            $("input[name='vatRate']")[0].value = "";
            $("input[name='taxRate']")[0].value = "";
            $("input[name='importTariff']")[0].value = "";
        }
    }
    form.render();
});


//监听上级目录下拉框
form.on("select(upDirectoryFilter)", function (data) {
    $("#directory").empty();
    let code = data.value;
    getDirectory(code);
})


function getDirectory(code) {
    let upDirectoryTemp;

    for (let i in selectdata) {
        if (code == selectdata[i].code) {
            upDirectoryTemp = selectdata[i];
        }
    }
    if (!isEmpty(upDirectoryTemp)) {
        let pidArr = []
        for (var i = 0; i < selectdata.length; i++) {
            if (upDirectoryTemp.id == selectdata[i].pid) {
                pidArr.push(selectdata[i]);
            }
        }
        if (pidArr.length <= 0) {
            pidArr.push(upDirectoryTemp);
        }

        form.render();
    }
}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["children"]){
            tmparr["children"]=  getAllJson(item["children"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }
    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        autoRow: true,
        filterable: true,
        radio: true,
        tree: {
            show: true,
            showFolderIcon: true,
            showLine: true,
            indent: 20,
            expandedKeys: [ -3 ],
            strict: false,
        },
        height: '300px',
        data: data,
        on: function(data){
            if(data.isAdd){
                return data.change.slice(0, 1)
            }
        },
    });
}

//json转tree
function toTree(data) {
    let result = []
    if(!Array.isArray(data)) {
        return result
    }
    let map = {};
    data.forEach(item => {
        map[item.id] = item;
    });
    data.forEach(item => {
        let parent = map[item.pid];
        if(parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}

//目录树
let productTreeList=[];

$(document).ready(function () {
    //获取目录下拉框数据
    getSelectDirectoryData();

    //产品目录
    let treeList = toTree(selectdata);
    if(treeList){
        let productTree = getAllJson(treeList);
        productTreeList=getxmselect("#directory","cataCode", productTree)
    }else {
        productTreeList=getxmselect("#directory","cataCode", [])
    }

    //获取合并后的数据
    let margeData = getMargeData();
    //主产品信息
    let obj = margeData.mainInfo;
    let upCataCodePath = obj.upCataCode;
    let upCataCode = "";
    if (!isEmpty(upCataCodePath)) {
        for (let i in selectdata) {
            if (upCataCodePath == selectdata[i].path) {
                upCataCode = selectdata[i].code;
                break;
            }
        }
    }
    getDirectory(upCataCode);
    form.val("editor-form", {
        "code": obj.code,
        "chinaName": obj.chinaName,
        "englishName": obj.englishName,
        "hgCode": obj.hgCode,
        "customerCode": obj.customerCode,
        "remark": obj.remark
    });
    $("#upDirectory").val(upCataCode);
    productTreeList.setValue([cataCode]);

    let hgname = "";
    let hg = obj.hgCode;
    for (var i = 0; i < hs.length; i++) {
        if (hg == hs[i].code) {
            hgname = hs[i].name;
            $("input[name='vatRate']")[0].value = hs[i].vatRate;
            $("input[name='taxRate']")[0].value = hs[i].taxRate;
            $("input[name='importTariff']")[0].value = hs[i].importTariff;
            break;
        } else {
            $("input[name='vatRate']")[0].value = "";
            $("input[name='taxRate']")[0].value = "";
            $("input[name='importTariff']")[0].value = "";
        }
    }

    let tpdata = JSON.parse(obj.img);
    for (var i = 0; i < tpdata.length; i++) {
        img_count++;
        let newImg = '<div class="img_tj">' +
            '<div class="img_wdiv"><img src="' + tpdata[i] + '" id="imgUpload_' + img_count + '"></div>' +
            '<div class="de_div">' +
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="imgUpload_sc_' + img_count + '"></i>' +
            '</div>' +
            '</div>';
        $('#addimgdiv').append(newImg);
        imgs.push(tpdata[i]);
        uploadImgRender("#imgUpload_" + img_count, "#imgUpload_sc_" + img_count);
    }

    let fjdata = JSON.parse(obj.wj);
    for (var i = 0; i < fjdata.length; i++) {
        file_count++;
        let filename = fjdata[i].split("filename=")[1];
        let filenames = fjdata[i].split("pathname=")[1].split("&filename=");
        let pathA = filenames[0];//"c:/a/a/"
        let fnas = filenames[1].split("&originalFileName=");
        filename = fnas[1];
        pathA = pathA + "/" + fnas[0];
        let newFile = '<div class="img_tj">' +
            '<div class="file_wdiv"><a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + filename + '" id="file_span' + file_count + '" download="' + filename +
            '" href="javascript:void(0);" onclick="onLineFile(\'' + pathA + '\');">' + filename + '</a>' +
            '<a type="button" class="layui-btn" id="fileUpload_' + file_count + '"><i class="layui-icon"></i>上传附件</a></div>' +
            '<div class="de_div">' +
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;margin-right:20px;" ' +
            'id="fileUpload_sc_' + file_count + '"></i>' +
            '<i class="layui-icon layui-icon-download-circle" style="font-size: 30px; color: #000000;line-height: 30px;" onclick="downFileLoadNew(\'' + filename + '\',\'' + pathA + '\');"></i>' +
            '</div>' +
            '</div>';
        $('#addfilediv').append(newFile);
        wjs.push(fjdata[i]);
        uploadFileRender("#fileUpload_" + file_count, "#fileUpload_sc_" + file_count, "#file_span" + file_count);
    }

    //规格信息
    let specList = margeData.specList;
    table.reload("producttableid", {data: specList});
    //配件信息
    let partsList = margeData.partsList;
    table.reload("productsatableid", {data: partsList});
    //供应商信息
    let supplierList = margeData.supplierList;
    if(supplierList){
        table.reload("asuppliertableid", {data: supplierList});
    }

    form.render();
});

//获取合并后的数据
function getMargeData() {
    let margeInfo = window.sessionStorage.getItem("margeInfo");
    let margeData = [];
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data: margeInfo,
        url:"productmaininfo/getMargeData",
        async: false,
        success:function(res){
            if(res.status == 200){
                margeData = res.data;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    return margeData;
}

//规格数据
let specData = [];
table.render({
    elem: '#productselect'
    , data : specData
    , toolbar: '#producttoolbar'
    , cols: [[
          {field: 'code', title: '规格编码', width: 120, sort: true}
        , {field: 'productCode', title: '主品编码', hide: true, width: 120, sort: true}
        , {field: 'categoryName', title: '种类', width: 120, sort: true}
        , {field: 'categoryCode', title: '种类编码', hide: true, width: 120, sort: true}
        , {field: 'moldCategoryName', title: '模具类别', width: 120, sort: true}
        , {field: 'moldCategoryCode', title: '模具类别编码', hide: true, width: 120, sort: true}
        , {field: 'firstCategoryName', title: '品类', width: 120, sort: true}
        , {field: 'firstCategoryCode', title: '品类编码', hide: true, width: 120, sort: true}
        , {field: 'secondaryCategoryName', title: '规格', width: 120, sort: true}
        , {field: 'secondaryCategoryCode', title: '规格编码', hide: true, width: 120, sort: true}
        , {field: 'threeCategoryName', title: '材质', width: 120, sort: true}
        , {field: 'threeCategoryCode', title: '材质编码', hide: true, width: 120, sort: true}
        , {field: 'craftName', title: '工艺', width: 120, sort: true}
        , {field: 'craftCode', title: '工艺编码', hide: true, width: 120, sort: true}
        , {field: 'colorOrderNumberName', title: '颜色订货号', width: 120, sort: true}
        , {field: 'colorOrderNumberCode', title: '颜色订货号编码', hide: true, width: 120, sort: true}
        , {field: 'customerLogoOrderNumber', title: '客户LOGO订货号', width: 120, sort: true}
        , {field: 'ge', title: '规格说明', width: 120, sort: true}
        , {field: 'chinaRemark', title: '中文描述', width: 120, sort: true}
        , {field: 'englishRemark', title: '英文描述', width: 120, sort: true}
        , {field: 'bzsm', title: '每托箱数', width: 120, sort: true}
        , {field: 'cpjz', title: '产品净重', width: 120, sort: true}
        , {field: 'cpmz', title: '产品毛重', width: 120, sort: true}
        , {field: 'colour', title: '颜色', width: 120, sort: true}
        , {field: 'dw', title: '单位', width: 120, sort: true}
        , {field: 'cgbz', title:'采购币种', width: 120, sort: true}
        , {field: 'cgcb', title:'含税出厂价', width: 120, sort: true}
        , {field: 'cgcbws', title:'未税出厂价', width: 120, sort: true}
        , {field: 'fob', title:'含税FOB价', width: 120, sort: true}
        , {field: 'cshh', title:'未税FOB价', width: 120, sort: true}
        , {field: 'wbzc', title: '外包装长mm', width: 120, sort: true}
        , {field: 'wbzk', title: '外包装宽mm', width: 120, sort: true}
        , {field: 'wbzg', title: '外包装高mm', width: 120, sort: true}
        , {field: 'wbzsl', title: '每箱数量', width: 120, sort: true}
        , {field: 'tj', title: '体积', width: 120, sort: true}
        , {field: 'hq40zl', title: '40HQ装量', width: 120, sort: true}
        , {field: 'gp20', title: '20GP', width: 120, sort: true}
        , {field: 'gp40', title: '40GP', width: 120, sort: true}
        , {field: 'lclpx', title: 'LCL拼箱', width: 120, sort: true}
        /*, {fixed: 'right', width: 150, align: 'center', toolbar: '#productup', title: '操作'}*/
    ]]
    , id: 'producttableid'
    , page: false
    , height: 300
    , done: function (res, curr, count) {

        $("[data-field = 'cgbz']").children().each(function () {
            for (var i = 0; i < cgbz.length; i++) {
                if ($(this).text() == cgbz[i].code) {
                    $(this).text(cgbz[i].name);
                }
            }
        })
        $("[data-field = 'dw']").children().each(function () {
            for (var i = 0; i < dw.length; i++) {
                if ($(this).text() == dw[i].code) {
                    $(this).text(dw[i].name);
                }
            }
        })
        $("[data-field = 'gys']").children().each(function () {
            for (var i = 0; i < gys.length; i++) {
                if ($(this).text() == gys[i].code) {
                    $(this).text(gys[i].name);
                }
            }
        })


    }
});

//配件数据
let partsData = [];
table.render({
    elem: '#productsaselect'
    , data: partsData
    , toolbar: '#productsatoolbar'
    , cols: [[
         {field: 'productCode', title: '产品编码', templet: '#productcodeselect', style: "color:#009688"}
        , {field: 'fjCode', title: '规格编码', sort: true}
        , {field: 'cpbl', title: '成品比例', edit: 'text'}
        , {field: 'pjbl', title: '配件比例', edit: 'text'}
        , {field: 'chinaname', title: '中文名称', sort: true}
        , {field: 'englishname', title: '英文名称', sort: true}
        , {field: 'mz', title: '毛重', sort: true}
        , {field: 'jz', title: '净重', sort: true}
        , {field: 'tj', title: '体积', sort: true}
        , {field: 'zhuge', title: '所属规格编码', hide: true, width: 120, sort: true}
        , {field: 'mainProductCode', title: '所属主产品编号', hide: true, width: 120, sort: true}
        /*, {fixed: 'right', width: 150, align: 'center', toolbar: '#productsaup', title: '操作'}*/
    ]]
    , id: 'productsatableid'
    , page: false
    , height: 400
});

let suppData = [];
table.render({
    elem: '#asupplierselect',
    data: suppData,
    cols: [[
         {field: 'code', title: '供应商', sort: true}
        , {field: 'fob', title: '含税FOB价', sort: true}
        , {field: 'cshh', title: '未税FOB价', sort: true}
        , {field: 'cgbz', title: '采购币种', sort: true}
        , {field: 'cgcb', title: '含税出厂价', sort: true}
        , {field: 'catalog', title: '未税出厂价', sort: true}
        , {field: 'createDate', title: '创建日期', sort: true}
        , {field: 'updateDate', title: '修改日期', sort: true}
        /*, {fixed: 'right', width: 150, align: 'center', toolbar: '#asupplierup', title: '操作'}*/
    ]]
    , id: 'asuppliertableid'
    , page: false
    , height: 300
    , done: function (res, curr, count) {

        $("[data-field = 'cgbz']").children().each(function () {

            for (var i = 0; i < cgbz.length; i++) {
                if ($(this).text() == cgbz[i].code) {
                    $(this).text(cgbz[i].name);
                }
            }
        })

        $("[data-field = 'code']").children().each(function () {
            for (var i = 0; i < gys.length; i++) {
                if ($(this).text() == gys[i].code) {
                    $(this).text(gys[i].name);
                }
            }
        })

        $("[data-field = 'catalog']").children().each(function () {
            if ($(this).text() == cataCode) {
                $(this).text(cataCodeName);
            }
        })

    }


});

table.render({
    elem: '#boxGaugeSelect'
    , data: []
    , cols: [[
          {field: 'productCode', title: '产品编码', hide: true}
        , {field: 'specificationCode', title: '规格编码', hide: true}
        , {field: 'containerCode', title: '货柜型号', hide: true}
        , {field: 'containerName', title: '货柜型号', sort: true}
        , {field: 'boxNum', title: '箱数', sort: true}
        , {field: 'boxGrossWeight', title: '单箱毛重', sort: true}
        , {field: 'boxNetWeight', title: '单箱净重', sort: true}
        , {field: 'boxNumPallet', title: '纸箱数量/托数', sort: true}
        , {field: 'numPallet', title: '数量/托数', sort: true}
        , {field: 'createDate', title: '创建日期', sort: true}
        , {field: 'updateDate', title: '修改日期', sort: true}
        /*, {fixed: 'right', width: 150, align: 'center', toolbar: '#boxGaugeSet', title: '操作'}*/
    ]]
    , id: 'boxGaugeTableId'
    , page: false
    , height: 300
});

//---日志
table.render({
    elem: '#infoselect'
    , type: "get"
    , url: "productlog/selectByPage"
    , where: {
        "code": code
    }
    , cols: [[
        {field: 'type', title: '操作类型', sort: true}
        , {field: 'optioner', title: '操作员名称', sort: true}
        , {field: 'time', title: '更新日期', sort: true}
        , {field: 'content', title: '操作内容', sort: true}
    ]]
    , id: 'infoselecttableid'
    , page: true
    , height: 350
});

//监听提交---保存
form.on('submit(form-save)', function (data) {
    //校验产品编码是否存在
    let flag = isExistCode(data.field.code);
    if(flag){
        layer.msg("编码重复!");
        return false;
    }
    //成品新增 (1:成品 2:配件)
    data.field["productType"] = 1;
    //1.主信息保存
    debugger;
    let parentDataSaveFlag = savemain(data.field);

    //2.规格信息保存
    //获取规格数据
    let specData = table.cache["producttableid"];
    let specDataSaveFlag = saveSpecData(specData[0]);

    //3.配件信息保存
    //获取配件数据
    let specPartsData = table.cache["productsatableid"];
    let specPartsDataSaveFlag = saveSpecParts(specPartsData);

    if (parentDataSaveFlag && specDataSaveFlag && specPartsDataSaveFlag) {
        layer.msg('保存成功');
    } else {
        layer.msg('保存失败');
    }
     setTimeout(function () {
         //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/product.jsp");
        parent.intab("views/jsp/BasicData/product.jsp", "产品")
        parent.detab("views/jsp/BasicData/tpl/newProductMarge.jsp", "产品合并");
     },1000)
    return false;
});

//校验产品编码是否存在
function isExistCode(code) {
    let flag = false;
    $.ajax({
        type : 'get',
        data:{"code":code},
        url:'productmaininfo/isexit',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                if(da.data){
                    flag = true;
                }
            }
        }
    });
    return flag;
}

//规格数据保存
function saveSpecData(specData) {
    let tf = false;
    $.ajax({
        type: 'post',
        data: JSON.stringify(specData),
        url: 'productfjinfo/savefj',
        dataType: "json",
        contentType: 'application/json',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data > 0;
            }else {
                layer.msg(da.msg, {icon: 5});
            }
        }
    });
    return tf;
}
//配件新增、修改
function saveSpecParts(dataInfo) {
    let saveFlag = false;
    for (let i in dataInfo) {
        $.ajax({
            type: 'post',
            data: JSON.stringify(dataInfo[i]),
            url: 'productfjge/savege',
            dataType: "json",
            contentType: 'application/json',
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    saveFlag = da.data > 0;
                }
            }
        });
        if (!saveFlag) {
            break;
        }
    }
    return saveFlag;
}

//可用于修改动态生成 图片
$("#newimg").on('click', function () {
    img_count++;
    var newImg = '<div class="img_tj">' +
        '<div class="img_wdiv"><img src="statics/images/layui-logo.jpg" id="imgUpload_' + img_count + '"></div>' +
        '<div class="de_div">' +
        '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="imgUpload_sc_' + img_count + '"></i>' +
        '</div>' +
        '</div>';
    $('#addimgdiv').append(newImg);
    uploadImgRender("#imgUpload_" + img_count, "#imgUpload_sc_" + img_count);
});

function uploadImgRender(e, uploadimd) {
    var uploadImg = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        , data: {"fileType": "productimg"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                console.log(uploadImg);
                $(e).attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status != 200) {
                return layer.msg('上传失败');
            }

            var ftpPath = res.data[0].ftpPath;
            var fileName = res.data[0].fileName;
            var src = getFtpPath(ftpPath, fileName);
            imgs.push(src);
            return layer.msg('上传成功');
        }
        , error: function () {
            //演示失败状态，并实现重传
            var img_wdiv = $(e).parent();
            var img_sb = img_wdiv.find('.img_sb');
            if (img_sb.length == 0) {
                img_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                img_wdiv.find('.demo-reload').on('click', function () {
                    uploadImg.upload();
                });
            }
        }
    });

    $(uploadimd).on('click', function () {
        let pathD = $(e).attr("src")
        for (let i = 0; i < imgs.length; i++) {
            if (imgs[i] == pathD) {
                imgs.splice(i, 1);
            }
        }
        $(uploadimd).parent().parent().remove();
    })
}


//文件
$("#newfile").on('click', function () {
    file_count++;
    var newFile = '<div class="img_tj">' +
        '<div class="file_wdiv"><div style="height: 25px;"><a style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="file_span' + file_count + '" id="file_span' + file_count + '" ' +
        '   onclick="getPathOnLine(this);"></a>&nbsp;</div>' +
        '<a type="button" class="layui-btn" id="fileUpload_' + file_count + '">  ' +
        ' <i class="layui-icon"></i>上传附件</a></div>' +
        '<div class="de_div">' +
        '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;margin-right:20px;"  id="fileUpload_sc_' + file_count + '"></i>' +

        '<i class="layui-icon layui-icon-download-circle" style="font-size: 30px; color: #000000;line-height: 30px;display: none;"   id="fileDownload_sc_' + file_count + '" ></i>' +
        '</div>' +
        '</div>';

    $('#addfilediv').append(newFile);
    uploadFileRender("#fileUpload_" + file_count, "#fileUpload_sc_" + file_count, "#file_span" + file_count, "#fileDownload_sc_" + file_count);
});

function getPathOnLine(path) {
    for (var i = 0; i < wjs.length; i++) {
        var ph = wjs[i];
        if (ph.indexOf(path.text) != -1) {
            var filename = ph.split("filename=")[1];
            var filenames = ph.split("pathname=")[1].split("&filename=");
            var pathA = filenames[0];//"c:/a/a/"
            var fnas = filenames[1].split("&originalFileName=");
            filename = fnas[1];
            pathA = pathA + "/" + fnas[0];
            onLineFile(pathA);
        }
    }

}

function uploadFileRender(e, uploadimd, name, download) {
    var uploadfile = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        , data: {"fileType": "productwj"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(name).html(file.name);
                $(name).attr("title", file.name);
                $(download).css("display", "block");
            });
        }
        , done: function (res) {


            //如果上传失败
            if (res.status != 200) {
                return layer.msg('上传失败');
            }
            var ftpPath = res.data[0].ftpPath;
            var fileName = res.data[0].fileName;
            var originalFileName = res.data[0].originalFileName;
            fileName = fileName + "&originalFileName=" + originalFileName;
            var src = getFtpPath(ftpPath, fileName);
            wjs.push(src);

            return layer.msg('上传成功');

        }
        , error: function () {
            //演示失败状态，并实现重传
            var file_wdiv = $(e).parent();
            var img_sb = file_wdiv.find('.img_sb');
            if (img_sb.length == 0) {
                file_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                file_wdiv.find('.demo-reload').on('click', function () {
                    uploadfile.upload();
                });
            }
        }
    });


//移除
    $(uploadimd).on('click', function () {
        let pathD = $(name)[0].innerText;
        for (let i = 0; i < wjs.length; i++) {
            if (wjs[i].indexOf(pathD)) {//wjs[i]==pathD){
                wjs.splice(i, 1);
            }
        }
        $(uploadimd).parent().parent().remove();
    })
    //下载
    $(download).on('click', function () {
        downFileload2($(name)[0].href, $(name)[0].text);
    })
}

function savemain(data) {
    maincode = data.code;
    for (let i in selectdata) {
        if (data.upCataCode == selectdata[i].code) {
            data.upCataCode = selectdata[i].path;
        }
    }
    window.sessionStorage.setItem("code", maincode);
    code = window.sessionStorage.getItem("code");
    data.img = JSON.stringify(imgs);
    data.wj = JSON.stringify(wjs);
    let tf = false;
    $.ajax({
        type: 'post',
        data: JSON.stringify(data),
        url: 'productmaininfo/savemain',
        dataType: "json",
        contentType: 'application/json',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data > 0;
            }
        }
    });
    return tf;
}

//关闭
$("#shutdown").on('click', function () {
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/product.jsp");
        parent.intab("views/jsp/BasicData/product.jsp", "产品")
        parent.detab("views/jsp/BasicData/tpl/newProductMarge.jsp", "产品合并");
    }, 1000)
})


//图片、文件上传
function upload() {
    upload.render({
        elem: '#logoadd'
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        , data: {"fileType": "customerlogo"}//头像
        , before: function (obj) {

        }
        , done: function (res) {
            //如果上传失败
            if (res.status != 200) {
                return layer.msg('上传失败');
            } else {
                var ftpPath = res.data[0].ftpPath;
                var fileName = res.data[0].fileName;
                var src = getFtpPath(ftpPath, fileName);
                $("#userphotos").attr('src', src);
                $("input[name='logo']")[0].value = src;
            }
            //上传成功
        }
        , error: function () {
            layer.msg('上传失败,请稍后重试')
        }
    })
}


//获取所有供应商
function getgys() {
    let gys = [];
    $.ajax({
        type: 'get',
        url: 'customer2/getAllGys',
        dataType: "json",
        async: false,
        success: function (da) {
            if (da.status == 200) {
                for (var i = 0; i < da.data.length; i++) {
                    var obj = {};
                    obj.code = da.data[i].code;
                    obj.name = da.data[i].name;
                    gys.push(obj);
                }

            }
        }
    });
    return gys;
}

function getoption(objs) {
    var stoptions = "<option value=''></option>";
    for (var i = 0; i < objs.length; i++) {
        stoptions += "<option value='" + objs[i].code + "'>" + objs[i].name + "</option>";
    }
    return stoptions;
}

function getoptionHs(objs) {
    var stoptions = "<option value=''></option>";
    for (var i = 0; i < objs.length; i++) {
        stoptions += "<option value='" + objs[i].code + "'>" + objs[i].name + "[" + objs[i].code + "]</option>";
    }
    return stoptions;
}

//获取目录下拉框数据
function getSelectDirectoryData() {
    $.ajax({
        type: 'get',
        url: 'productcatalog/getProductDirectoryInfo',
        dataType: "json",
        async: false,
        success: function (da) {
            if (da.status == 200) {
                selectdata = da.data;
            }
        }
    });
}

//生成临时id
function GenNonDuplicateID(randomLength) {
    return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "" || obj == 0) {
        return true;
    } else {
        return false;
    }
}

function isNumber(val) {
    let regPos = /^\d+(\.\d+)?$/; //非负浮点数
    let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

